﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections;

namespace YTBZ.PUB.Common
{
    public class WebUtil : Page
{
    // Fields
    internal static readonly string AllowExt = "jpe|jpeg|jpg|png|tif|tiff|bmp|gif|wbmp|swf|psd";

    // Methods
    public static bool CheckValidExt(string sExt)
    {
        string[] strArray = AllowExt.Split(new char[] { '|' });
        foreach (string str in strArray)
        {
            if (str.ToLower() == sExt.Replace(".", ""))
            {
                return true;
            }
        }
        return false;
    }

    public static string ConvertUrl(Page page, string html)
    {
        MatchCollection matchs = Regex.Matches(html, "<(a|link|img|script|input|form).[^>]*(href|src|action)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)[^>]*>", RegexOptions.IgnoreCase);
        foreach (Match match in matchs)
        {
            if (match.Groups[match.Groups.Count - 2].Value.IndexOf("~") != -1)
            {
                string newValue = page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value);
                html = html.Replace(match.Groups[match.Groups.Count - 2].Value, newValue);
            }
        }
        return html;
    }

    private static ImageCodecInfo GetCodecInfo(string mimeType)
    {
        ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
        foreach (ImageCodecInfo info in imageEncoders)
        {
            if (info.MimeType == mimeType)
            {
                return info;
            }
        }
        return null;
    }

        /// <summary>
        /// 得到cookie里的值

        /// </summary>
        /// <param name="strName">cookie名字</param>
        /// <returns></returns>
    public static string GetCookie(string strName)
    {
        if ((HttpContext.Current.Request.Cookies != null) && (HttpContext.Current.Request.Cookies[strName] != null))
        {
            return HttpContext.Current.Request.Cookies[strName].Value.ToString();
        }
        return "";
    }
        /// <summary>
        /// 得到主机的域名和端口号

        /// </summary>
        /// <returns></returns>
    public static string GetCurrentFullHost()
    {
        HttpRequest request = HttpContext.Current.Request;
        if (!request.Url.IsDefaultPort)
        {
            return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
        }
        return request.Url.Host;
    }

    public static float GetFloat(string strName, float defValue)
    {
        if (GetQueryFloat(strName, defValue) == defValue)
        {
            return GetFormFloat(strName, defValue);
        }
        return GetQueryFloat(strName, defValue);
    }

    public static float GetFormFloat(string strName, float defValue)
    {
        return StringHelper.StrToFloat(HttpContext.Current.Request.Form[strName], defValue);
    }

    public static int GetFormInt(string strName, int defValue)
    {
        return StringHelper.StrToInt(HttpContext.Current.Request.Form[strName], defValue);
    }

    public static string GetFormString(string strName)
    {
        if (HttpContext.Current.Request.Form[strName] == null)
        {
            return "";
        }
        return HttpContext.Current.Request.Form[strName];
    }

    public static string GetHost()
    {
        return HttpContext.Current.Request.Url.Host;
    }

    public static string GetHtmime(string ext)
    {
        Hashtable hashtable = new Hashtable();
        switch (ext.ToLower())
        {
            case ".jpe":
            case ".jpeg":
            case ".jpg":
                hashtable[ext] = "image/jpeg";
                break;

            case ".png":
                hashtable[ext] = "image/png";
                break;

            case ".tif":
            case ".tiff":
                hashtable[ext] = "image/tiff";
                break;

            case ".bmp":
                hashtable[ext] = "image/bmp";
                break;

            case ".gif":
                hashtable[ext] = "image/gif";
                break;

            case ".swf":
                hashtable[ext] = "image/swf";
                break;

            case ".wbmp":
                hashtable[ext] = "image/wbmp";
                break;

            case ".psd":
                hashtable[ext] = "image/psd";
                break;
        }
        return (string) hashtable[ext];
    }

    public static int GetInt(string strName, int defValue)
    {
        if (GetQueryInt(strName, defValue) == defValue)
        {
            return GetFormInt(strName, defValue);
        }
        return GetQueryInt(strName, defValue);
    }

    public static string GetIP()
    {
        string ip = string.Empty;
        ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        switch (ip)
        {
            case null:
            case "":
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                break;
        }
        if ((ip == null) || (ip == string.Empty))
        {
            ip = HttpContext.Current.Request.UserHostAddress;
        }
        if (!(((ip != null) && (ip != string.Empty)) && IsIP(ip)))
        {
            return "0.0.0.0";
        }
        return ip;
    }
        /// <summary>
        /// 得到页面名称
        /// </summary>
        /// <returns></returns>
    public static string GetPageName()
    {
        string[] strArray = HttpContext.Current.Request.Url.AbsolutePath.Split(new char[] { '/' });
        return strArray[strArray.Length - 1].ToLower();
    }
        /// <summary>
        /// 得到页面参数个数
        /// </summary>
        /// <returns></returns>
    public static int GetParamCount()
    {
        return (HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count);
    }

    public static float GetQueryFloat(string strName, float defValue)
    {
        return StringHelper.StrToFloat(HttpContext.Current.Request.QueryString[strName], defValue);
    }

    public static int GetQueryInt(string strName, int defValue)
    {
        return StringHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], defValue);
    }

    public static string GetQueryString(string strName)
    {
        if (HttpContext.Current.Request.QueryString[strName] == null)
        {
            return "";
        }
        return HttpContext.Current.Request.QueryString[strName];
    }
        /// <summary>
        /// 得到当前地址
        /// </summary>
        /// <returns></returns>
    public static string GetRawUrl()
    {
        return HttpContext.Current.Request.RawUrl;
    }

    public static string GetServerString(string strName)
    {
        if (HttpContext.Current.Request.ServerVariables[strName] == null)
        {
            return "";
        }
        return HttpContext.Current.Request.ServerVariables[strName].ToString();
    }

    public static string GetSession(string strName)
    {
        if ((HttpContext.Current.Session != null) && (HttpContext.Current.Session[strName] != null))
        {
            return HttpContext.Current.Session[strName].ToString();
        }
        return "";
    }

    public static int GetSessionInt(string strName, int defaultValue)
    {
        if ((HttpContext.Current.Session != null) && (HttpContext.Current.Session[strName] != null))
        {
            return StringHelper.StrToInt(HttpContext.Current.Session[strName]);
        }
        return defaultValue;
    }

    public static string GetString(string strName)
    {
        if ("".Equals(GetQueryString(strName)))
        {
            return GetFormString(strName);
        }
        return GetQueryString(strName);
    }

    public static string GetUrl()
    {
        return HttpContext.Current.Request.Url.ToString();
    }
        /// <summary>
        /// 上一张页面地址
        /// </summary>
        /// <returns></returns>
    public static string GetUrlReferrer()
    {
        string str = null;
        try
        {
            str = HttpContext.Current.Request.UrlReferrer.ToString();
        }
        catch
        {
        }
        if (str == null)
        {
            return "";
        }
        return str;
    }

    public static bool InIPArray(string ip, string[] iparray)
    {
        string[] strArray = StringHelper.SplitString(ip, ".");
        for (int i = 0; i < iparray.Length; i++)
        {
            string[] strArray2 = StringHelper.SplitString(iparray[i], ".");
            int num2 = 0;
            for (int j = 0; j < strArray2.Length; j++)
            {
                if (strArray2[j] == "*")
                {
                    return true;
                }
                if ((strArray.Length > j) && (strArray2[j] == strArray[j]))
                {
                    num2++;
                }
                else
                {
                    break;
                }
            }
            if (num2 == 4)
            {
                return true;
            }
        }
        return false;
    }

    public static bool IsBrowserGet()
    {
        string[] strArray = new string[] { "ie", "opera", "netscape", "mozilla" };
        string str = HttpContext.Current.Request.Browser.Type.ToLower();
        for (int i = 0; i < strArray.Length; i++)
        {
            if (str.IndexOf(strArray[i]) >= 0)
            {
                return true;
            }
        }
        return false;
    }

    public static bool IsGet()
    {
        return HttpContext.Current.Request.HttpMethod.Equals("GET");
    }

    public static bool IsIP(string ip)
    {
        return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    public static bool IsPost()
    {
        return HttpContext.Current.Request.HttpMethod.Equals("POST");
    }

    public static bool IsSearchEnginesGet()
    {
        string[] strArray = new string[] { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom" };
        string str = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
        for (int i = 0; i < strArray.Length; i++)
        {
            if (str.IndexOf(strArray[i]) >= 0)
            {
                return true;
            }
        }
        return false;
    }

    public static string ReadApplication(string strName)
    {
        if (HttpContext.Current.Application[strName] != null)
        {
            return HttpContext.Current.Application[strName].ToString();
        }
        return null;
    }

    public static void RemoveApplication(string strName)
    {
        if (HttpContext.Current.Application[strName] != null)
        {
            HttpContext.Current.Application.Remove(strName);
        }
    }

    public static void RemoveCache(string key)
    {
        if (HttpRuntime.Cache[key] != null)
        {
            HttpRuntime.Cache.Remove(key);
        }
    }

    public static void RemoveCookie(string name)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
        if (cookie != null)
        {
            HttpContext.Current.Request.Cookies.Remove(name);
        }
    }

    public static string ReplaceUrlBadChar(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return "";
        }
        string strContent = "+,',--,(,),<,>,[,],{,},\\,;,,\",\"\"";
        string[] strArray = StringHelper.SplitString(strContent, ",");
        string str3 = str;
        for (int i = 0; i < strArray.Length; i++)
        {
            if (strArray[i].Length > 0)
            {
                str3 = str3.Replace(strArray[i], "");
            }
        }
        return str3;
    }

    public static void SaveImage(System.Drawing.Image image, string savePath, ImageCodecInfo ici)
    {
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
        image.Save(savePath, ici, encoderParams);
        encoderParams.Dispose();
    }

    public static void SaveRequestFile(string path)
    {
        if (HttpContext.Current.Request.Files.Count > 0)
        {
            HttpContext.Current.Request.Files[0].SaveAs(path);
        }
    }

    public static void ToThumbnailImages(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, string backgroundcolor)
    {
        string path = sourceImagePath;
        string str2 = thumbnailImagePath;
        int width = thumbnailImageWidth;
        string sExt = path.Substring(path.LastIndexOf(".")).ToLower();
        if (path.ToString() == string.Empty)
        {
            throw new NullReferenceException("SourceImagePath is null!");
        }
        if (!CheckValidExt(sExt))
        {
            throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]", "SourceImagePath");
        }
        System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(path));
        int height = (width / 4) * 3;
        int num3 = image.Width;
        int num4 = image.Height;
        if ((((double) num3) / ((double) num4)) >= 1.3333333730697632)
        {
            height = (num4 * width) / num3;
        }
        else
        {
            width = (num3 * height) / num4;
        }
        if ((width >= 1) && (height >= 1))
        {
            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            Graphics graphics = Graphics.FromImage(bitmap);
            if (string.IsNullOrEmpty(backgroundcolor))
            {
                graphics.Clear(Color.Transparent);
            }
            else
            {
                ColorConverter converter = new ColorConverter();
                Color color = new Color();
                color = (Color) converter.ConvertFromString(backgroundcolor);
                graphics.Clear(color);
            }
            graphics.DrawImage(image, new Rectangle(0, 0, width, height));
            image.Dispose();
            try
            {
                try
                {
                    string str4 = (str2 == null) ? path : str2;
                    SaveImage(bitmap, HttpContext.Current.Server.MapPath(str4), GetCodecInfo(GetHtmime(sExt)));
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }
        }
    }

    public static void ToThumbnailImages(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, int thumbnailImageHeight, string backgroundcolor)
    {
        string path = sourceImagePath;
        string str2 = thumbnailImagePath;
        int num = thumbnailImageWidth;
        string sExt = path.Substring(path.LastIndexOf(".")).ToLower();
        if (path.ToString() == string.Empty)
        {
            throw new NullReferenceException("SourceImagePath is null!");
        }
        if (!CheckValidExt(sExt))
        {
            throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]", "SourceImagePath");
        }
        System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(path));
        Bitmap bitmap = new Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);
        int y = 0;
        int x = 0;
        int width = image.Width;
        int height = image.Height;
        float num6 = ((float) thumbnailImageHeight) / ((float) thumbnailImageWidth);
        float num7 = ((float) image.Height) / ((float) image.Width);
        if (num6 > num7)
        {
            x = 0;
            y = (int) ((thumbnailImageHeight - (num7 * thumbnailImageWidth)) / 2f);
            width = thumbnailImageWidth;
            height = (int) (num7 * thumbnailImageWidth);
        }
        else if (num6 == num7)
        {
            x = 0;
            y = 0;
            width = thumbnailImageWidth;
            height = thumbnailImageHeight;
        }
        else
        {
            x = (int) ((thumbnailImageWidth - (((float) thumbnailImageHeight) / num7)) / 2f);
            y = 0;
            width = (int) (((float) thumbnailImageHeight) / num7);
            height = thumbnailImageHeight;
        }
        Graphics graphics = Graphics.FromImage(bitmap);
        if (string.IsNullOrEmpty(backgroundcolor))
        {
            graphics.Clear(Color.Transparent);
        }
        else
        {
            ColorConverter converter = new ColorConverter();
            Color color = new Color();
            color = (Color) converter.ConvertFromString(backgroundcolor);
            graphics.Clear(color);
        }
        Rectangle srcRect = new Rectangle(0, 0, image.Width, image.Height);
        Rectangle destRect = new Rectangle(x, y, width, height);
        graphics.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel);
        image.Dispose();
        try
        {
            try
            {
                string str4 = (str2 == null) ? path : str2;
                SaveImage(bitmap, HttpContext.Current.Server.MapPath(str4), GetCodecInfo(GetHtmime(sExt)));
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        finally
        {
            bitmap.Dispose();
            graphics.Dispose();
        }
    }

    public static string UrlDecode(string str)
    {
        return HttpUtility.UrlDecode(str);
    }

    public static string UrlEncode(string str)
    {
        return HttpUtility.UrlEncode(str);
    }

    public static void WriteApplication(string strName, string strValue)
    {
    }

    public static void WriteCookie(string strName, string strValue)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        if (cookie == null)
        {
            cookie = new HttpCookie(strName);
        }
        cookie.Value = strValue;
        HttpContext.Current.Response.AppendCookie(cookie);
    }

    public static void WriteCookie(string strName, string strValue, int expires)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        if (cookie == null)
        {
            cookie = new HttpCookie(strName);
        }
        cookie.Value = strValue;
        cookie.Expires = DateTime.Now.AddMinutes((double) expires);
        HttpContext.Current.Response.AppendCookie(cookie);
    }

    public static void WriteSession(string strName, string value)
    {
        HttpContext.Current.Session[strName] = value;
    }

    public static void EnableControl(bool enable, params WebControl[]  ctrs)
    {

        foreach (WebControl ctr in ctrs)
        {
            if(ctr!=null)
            ctr.Enabled = enable;
        }
    }
    /// <summary>
    /// 得到QueryString[strName]参数的解密值
    /// </summary>
    /// <param name="strName"></param>
    /// <returns></returns>
    public static string GetDesQueryString(string strName)
    {
        if (HttpContext.Current.Request.QueryString[strName] == null)
        {
            return null;
        }
        string str = HttpContext.Current.Request.QueryString[strName];
        if (str != "-1")
        {
            return str;
        }
        else
        {
            HttpContext.Current.Response.Write("<script type=\"text/javascript\" src=\"/Scripts/ymPrompt/ymPrompt.js\"></script>\n");
            HttpContext.Current.Response.Write("<link id=\"skin\" rel=\"stylesheet\" type=\"text/css\" href=\"" + StringHelper.strWebServer() + "Scripts/ymPrompt/skin/bluebar/ymPrompt.css\" />\n");
            HttpContext.Current.Response.Write("<Script Language=\"javascript\">\n");
            HttpContext.Current.Response.Write("ymPrompt.alert({title:'警告',message:'获取的参数无效！',handler:function(){     }});\n");//history.go(-1);
            HttpContext.Current.Response.Write("</Script>");
            HttpContext.Current.Response.End();
            return "";
        }
    }
}
}
